package com.hejjon.core.utils;


import com.hejjon.core.exception.BusinessException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class AESUtil {

    public static final String algorithm = "AES";
    public static final String transformation = "AES/ECB/PKCS5Padding";
    public static final String key = "DAIHAODAIHAO9527";

    /***
     * 加密
     * @param original 需要加密的参数
     * @return
     * @throws Exception
     */
    public static String encryptByAES(String original) {
        try {
            // 获取Cipher
            Cipher cipher = Cipher.getInstance(transformation);
            // 生成密钥
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
            // 指定模式(加密)和密钥
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            // 加密
            byte[] bytes = cipher.doFinal(original.getBytes());

            return Base64Util.encryptBASE64(bytes);

        } catch (Exception e) {
            throw new BusinessException("字符串 [ " + original + " ]加密出现异常: " + e.getMessage());
        }
    }

    /**
     * 解密
     * @param encrypted 需要解密的参数
     * @return 解密后的字符串
     * @throws Exception 异常
     */
    public static String decryptByAES(String encrypted) {

        // 获取Cipher
        Cipher cipher = null;

        try {

            cipher = Cipher.getInstance(transformation);
            // 生成密钥
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
            // 指定模式(解密)和密钥
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            // 解密
            byte[] bytes = cipher.doFinal(Base64Util.decryBASE64(encrypted));
            return new String(bytes);

        } catch (Exception e) {
            throw new BusinessException("字符串 [ " + encrypted + " ]解密出现异常: " + e.getMessage());
        }
    }

//    public static void main(String[] args) throws Exception {
//        //String s = encryptByAES("root");        //kgnvtzpgW5dXrxYEhSTcDw==
//        String s = "kgnvtzpgW5dXrxYEhSTcDw==";
//        System.out.println(s);
//        System.out.println(decryptByAES(s));
//    }

}
